package com.jnsw.testkotlin.utils;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.jnsw.testkotlin.MyApplication;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/14 0014.
 */

public class VolleyUtil {
    private static final String BASIC_URL = "http://10.80.5.247:8087/qzdj/";
    Context context;

    RequestQueue mQueue = Volley.newRequestQueue(MyApplication.Companion.getInstance()); //参数必须是application  不能动态传context

    public VolleyUtil() {

    }

    public synchronized void Login() { // 方法 必须带synchronized 关键字 否则无法传参
        StringRequest request = new StringRequest(Request.Method.POST, BASIC_URL + "Login",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            ArrayList<Map<String, Object>> maps = jsonObjectparseJSON(response);    //json格式的string  转换为数组
                            if (maps.size() != 0) {
//                        DataMessage dataMessage = new DataMessage(strtype, maps);
//                        DemoApp.getIns().eventBus.post(dataMessage);
                                System.out.println("success __________" + maps.toString());

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println("success __________" + response.toString());

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println("error-------------------" + error.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("username", "xz");
                map.put("password", "111");
                return map;
            }
        };
        mQueue.add(request);
    }

//    public synchronized void jsonLogin() { // JsonObjectRequest 传参方法与String不一致 此方法传参为null
//        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, BASIC_URL + "Login",
//                new Response.Listener<JSONObject>() {
//                    @Override
//                    public void onResponse(JSONObject response) {
//                        System.out.println("success __________" + response.toString());
//
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                System.out.println("error-------------------" + error.getMessage());
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                Map<String, String> map = new HashMap<String, String>();
//                map.put("username", "baiqiang");
//                map.put("password", "321");
//                return map;
//            }
//        };
//        mQueue.add(request);
//    }

    /**
     * 接收数据为jsonObject格式
     * 将jsonObject格式的字符串 转换为 list<map<>>
     *
     * @param str
     * @return
     * @throws Exception
     */
    private static ArrayList<Map<String, Object>> jsonObjectparseJSON(String str) throws Exception {
        ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        InputStream jsonStream = new ByteArrayInputStream(str.getBytes());
        byte[] data = StreamTool.read(jsonStream);
        String json = new String(data);


        JSONObject jsonObject = new JSONObject(json);
        Map<String, Object> map = new HashMap<String, Object>();
        Iterator<String> keys = jsonObject.keys();
        if (keys.hasNext()) {//判断是否有数据
            while (keys.hasNext()) {
                String key = keys.next();
                String title = jsonObject.getString(key);
                map.put(key, title);
            }
            list.add(map);
        }

        return list;
    }

    /**
     * 接收数据为jsonArry格式
     * 将jsonArry格式的字符串 转换为 list<map<>>
     *
     * @param str
     * @return
     * @throws Exception
     */
    private static ArrayList<Map<String, Object>> jsonArryParseJSON(String str) throws Exception {
        ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        InputStream jsonStream = new ByteArrayInputStream(str.getBytes());
        byte[] data = StreamTool.read(jsonStream);
        String json = new String(data);

        JSONArray jsonArray = new JSONArray(json);
        for (int i = 0; i < jsonArray.length(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                String title = jsonObject.getString(key);
                map.put(key, title);
            }
            list.add(map);
        }
        return list;
    }

    /**
     * InputStream 转换成byte数组
     */
    public static class StreamTool {
        public static byte[] read(InputStream inStream) throws Exception {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            inStream.close();
            return outputStream.toByteArray();
        }
    }
}
